import { ContractManageAPI } from '../common/type';
import { getProcessNodeTableColumns } from '../mconfig';
import { Empty, Table, message } from 'antd';
import { useContext, useEffect, useMemo, useState } from 'react';
import { ConractControllerContext } from '../common';
import { getMcontractProcessListService } from '../services';
import { OpenProcessUpdateModal } from './OpenProcessUpdateModal';
import { readReadShowFileService } from '@/services/BaseLayout';
import { getBaseUrl } from '@/services/urlconst';
import { getMcontractProcessService } from '../services';
import { DetailInfoViewTabsPaymentItem } from './DetailInfoViewTabsPaymentItem';

export const DetailInfoViewTabsAgree: React.FC<ContractManageAPI.IDetailInfoViewTabsAgree> = ({ tabsPaneInfoObj }) => {
  /** 引入上下文 */
  const { locationState, curRes, contractDetailInfo } = useContext(ConractControllerContext);

  /** 打开编辑添加履约关键节点弹框 */
  const [updateProcessModal, setUpdateProcessModal] = useState<Record<string, any>>({
    isShowModal: false,
    checkRowObj: {},
  });

  /** 获取数据回调 */
  const processCallback = (res: any) => {
    if (res && res?.msgFlag) {
    } else {
      message.error(res?.message);
    }
  };

  const [currentSelect, setCurrentSelect] = useState<any>();

  /** 获取数据回调 */
  const McontProcessCallback = (res: any) => {
    const data = [...newData];
    if (res && res?.msgFlag) {
      data.map((item) => {
        if (currentSelect?.id === item.id) {
          item.description = res.obj || [];
          item.loading = false;
        }
      });
    } else {
      data.map((item) => {
        if (currentSelect?.id === item.id) {
          item.loading = false;
        }
      });
      message.error(res?.message);
    }

    setNewData(data);
  };

  /** 引入获取数据接口 */
  const { getMcontractProcessListData, getMcontractProcessListLoading, getMcontractProcessListRun } = getMcontractProcessListService(processCallback);

  /**获取支付记录数据接口 */
  const { getMcontractProcessRun } = getMcontractProcessService(McontProcessCallback);

  /** 数据初始化 */
  useEffect(() => {
    if (tabsPaneInfoObj?.tabKeyType == 'nodePane') {
      getMcontractProcessListRun({
        id: locationState?.pageInfo?.pID ? locationState?.pageInfo?.pID : locationState?.pageInfo?.id || locationState?.id,
      });
    }
  }, [tabsPaneInfoObj, locationState]);

  /** 刷新页面 */
  const reloadManage = () => {
    getMcontractProcessListRun({
      id: locationState?.pageInfo?.pID ? locationState?.pageInfo?.pID : locationState?.pageInfo?.id,
    });
  };

  /** 打开添加编辑履约节点弹框 */
  const openProceTableModal = (resObj: Record<string, any>) => {
    setUpdateProcessModal({
      isShowModal: true,
      checkRowObj: resObj,
    });
  };

  /** 轻阅读预览 */
  const { readReadShowFileRun, readReadShowFileLoading } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  /** 表格配置 */
  const columnsMemo = useMemo(() => {
    return getProcessNodeTableColumns({
      curRes,
      detailInfo: locationState?.pIDDetailInfo,
      openProceTableModal,
      onOpenReadOfdWord,
    });
  }, [curRes, contractDetailInfo, getMcontractProcessListData]);

  const [newData, setNewData] = useState(getMcontractProcessListData);

  const getPayRecordData = async (expanded: boolean, record: Record<string, any>) => {
    if (expanded) {
      setCurrentSelect(record);
      const data = [...newData];

      data.map((item) => {
        if (record.id === item.id) {
          item.loading = true;
        }
      });
      setNewData(data);
      getMcontractProcessRun({
        processID: record.id,
        payCode: record.payCode,
      });
    }
  };

  useEffect(() => {
    setNewData(getMcontractProcessListData);
  }, [getMcontractProcessListData]);

  return (
    <>
      <div className="commonTabsBodyDom">
        <div className="tabsBodyInfoDom">
          <div className="list-table">
            {newData?.length ? (
              <Table
                size="small"
                bordered
                columns={columnsMemo}
                loading={getMcontractProcessListLoading || readReadShowFileLoading}
                scroll={{ x: 1200, y: 'true' }}
                dataSource={newData}
                rowKey={(res) => (res?.id ? res?.id : res?.key)}
                pagination={false}
                expandable={{
                  defaultExpandedRowKeys: newData?.map((item) => item?.id),
                  expandedRowRender: (record) => {
                    return (
                      <>
                        <DetailInfoViewTabsPaymentItem data={record.description || []} loading={record.loading || false} />
                        {/* <p style={{ margin: 0 }}>{record.description}哈哈哈</p> */}
                      </>
                    );
                  },
                  rowExpandable: (record) => true,
                  onExpand: (expanded, record) => getPayRecordData(expanded, record),
                }}
              />
            ) : (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
            )}
          </div>
        </div>
      </div>

      {/* 履约关键节点弹框 */}
      {updateProcessModal?.isShowModal && (
        <OpenProcessUpdateModal
          onClose={() => {
            setUpdateProcessModal({
              isShowModal: false,
              checkRowObj: {},
            });
          }}
          selectRowInfo={updateProcessModal?.checkRowObj}
          reloadManage={reloadManage}
        />
      )}
    </>
  );
};
